package app

import (
	"cade/src/bot/msg"
	"cade/src/core"
	"cade/src/core/log"
	"strings"
)

// ============================================================================

type bot_cmd_t []string
type bot_cmd_args_t []string

// ============================================================================

func parse_bot_cmd(text string) bot_cmd_t {
	arr := strings.Split(text, " ")
	return arr
}

func (self bot_cmd_t) execute(bot *Bot) bool {
	// find handler
	h := bot_handlers[self[0]]
	if h == nil {
		return false
	}

	// execute
	h(bot, bot_cmd_args_t(self[1:]))
	return true
}

func (self bot_cmd_args_t) check_string(i int) string {
	L := len(self)
	if i < L {
		return self[i]
	}

	return ""
}

func (self bot_cmd_args_t) check_int32(i int) int32 {
	L := len(self)
	if i < L {
		return core.Atoi32(self[i])
	}

	return 0
}

func (self bot_cmd_args_t) check_rest(i int) string {
	L := len(self)
	if i < L {
		return strings.Join(self[i:], " ")
	}

	return ""
}

// ============================================================================

// ============================================================================

var bot_handlers = map[string]func(*Bot, bot_cmd_args_t){
	"help": func(bot *Bot, args bot_cmd_args_t) {
		log.Info("list                  list rooms")
		log.Info("create name           create a room named 'name'")
		log.Info("enter  roomid         enter the room with roomid")
		log.Info("leave                 leave current room")
		log.Info("chat   text           send chat text")
	},

	"list": func(bot *Bot, args bot_cmd_args_t) {
		bot.SendMsg(&msg.C_ChatGetRoomList{})
	},

	"create": func(bot *Bot, args bot_cmd_args_t) {
		name := args.check_string(0)
		if name == "" {
			log.Error("create name")
			return
		}

		bot.SendMsg(&msg.C_ChatCreateRoom{
			Name: name,
		})
	},

	"enter": func(bot *Bot, args bot_cmd_args_t) {
		id := args.check_int32(0)
		if id == 0 {
			log.Error("enter roomid")
			return
		}

		bot.SendMsg(&msg.C_ChatEnterRoom{
			Id: id,
		})
	},

	"leave": func(bot *Bot, args bot_cmd_args_t) {
		bot.SendMsg(&msg.C_ChatLeaveRoom{})
	},

	"chat": func(bot *Bot, args bot_cmd_args_t) {
		text := args.check_rest(0)
		if text == "" {
			log.Error("chat text")
			return
		}

		bot.SendMsg(&msg.C_ChatSendText{
			Text: text,
		})
	},
}
